/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// This is the user object. Each user has a unique ID that
// allows it to be differentiated from all other clients on
// the same subscribed channel.
var user = {
uuid: null,
subscribed: false
};
 
 
// Cache frequent DOM references.
domC = {};
domC.messageLog =$("#chat-messages-inner");// $( "div.messageLog" );
domC.messageLogItems = domC.messageLog.find( "> ul" );
domC.form = $( "#chatForm" );
domC.formInput = domC.form.find( "input" );
domC.formSubmit =  domC.form.find( "button" );
 
 
// Override form submit to PUSH message.
domC.form.submit(
    function( event ){

        // Cancel the default event.
        event.preventDefault();

        // Make sure there is a message to send and that the
        // user is subscribed.
        if ( !user.subscribed || !domC.formInput.val().length ){

                // Nothing more we can do with this request.
                return;

        }

        // Send the message to the current channel.
        sendMessage($('#user').text() + '|'+ domC.formInput.val() +'|'+ $('#gravatar').text()) ;

        // Clear and focus the current message so the
        // user can keep typing new messages.
        domC.formInput.val( "" ).focus()  ;

    }
);
 
 
// I append the given message to the message log.
function appendMessage( messageIn, isFromMe ){
    var split = messageIn.split('|');

    var from = split[0];
    var message = split[1];
    var gravatar=split[2];
    // Creat the message item.
    var messageItem = document.createElement('p');

    var spanBlock = document.createElement("span");
     if (isFromMe){

        spanBlock.className= "msg-block" ;

    }
    else {

        spanBlock.className= "msg-block" ;

    }   
    var spanName = document.createElement("span");
    spanName.innerHTML = from;
    spanName.className= "name" ;
    var spanMsg = document.createElement("span");
    spanMsg.innerHTML = message;
    spanMsg.className= "msg" ;
    
    spanBlock.appendChild(spanName);
    spanBlock.appendChild(spanMsg);
    
    var elem = document.createElement("img");
    elem.setAttribute("src", "http://www.gravatar.com/avatar/"+gravatar+"?s=30&default=http://www.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=30");
    elem.setAttribute("height", "28");
    elem.setAttribute("width", "28");
    elem.setAttribute("alt", "");
    
    messageItem.appendChild(elem);
    messageItem.appendChild(spanBlock);
    
    // Add the message element to the list.
    domC.messageLogItems.append( messageItem );
 
}
 
 
// I send the given message to all subscribed clients.
function sendMessage( message ){
 
    // Immediately add the message to the UI so the user
    // feels like the interface is super responsive.
    appendMessage( message, true );

    // Push the message to PubNub. Attach the user UUID as
    // part of the message so we can filter it out when it
    // gets echoed back (as part of our subscription).
    PUBNUB.publish({
        channel: 'planning_'+$('#idProject').text(),// "hello_world2",
        message: {
            uuid: user.uuid,
            message: message
        }
    });
 
};
 
 
// I receive the message on the current channel.
function receiveMessage( message ){
 
    // Check to make sure the message is not just being
    // echoed back.
    if (message.uuid === user.uuid){

        // This message has already been handled locally.
        return;

    }

    // Add the message to the chat log.
    appendMessage( message.message );
 
}
 
 
// -------------------------------------------------- //
// -------------------------------------------------- //
 
 
// In order to initialize the system, we have to wait for the
// client to receive a UUID and for the subscription to the
// PubNub server to be established.
var init = $.when(
 
    // Get the user ID.
    getUUID(),

    // Subscribe to the PubNub channel.
    $.Deferred(
        function( deferred ){

            // When the PubNub connection has been
            // established, resolve the deferred container.
            PUBNUB.subscribe({
            channel:'planning_'+$('#idProject').text(),
            callback: receiveMessage,
            connect: deferred.resolve,
            error: deferred.fail
            });

        }
    )
 
);
 
// When the UUID has come back, prepare the user for use
// within the system.
init.done(
    function( uuid ){

        // Store the UUID with the user.
        user.uuid = uuid;

        // Flag the user as subscribed.
        user.subscribed = true;

        // Enable the message form.
        domC.formSubmit.removeAttr( "disabled" );

    }
);
 
 
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
 
 
// NOTE: The following are just PubNub utility methods that
// have been converted from callback-based responses to
// deferred-based promises.
 
 
// I get a UUID from the PUBNUB server. I return a promise
// of the value to be returned.
function getUUID(){

    // Since the core UUID method uses a callback, we need to
    // create our own intermediary deferred object to wire
    // the two workflows together.
    var deferred = $.Deferred();

    // Ask PubNub for a UUID.
    PUBNUB.uuid(
        function( uuid ){

            // Resolve the uuid promise.
            deferred.resolve( uuid );

        }
    );

    // Return the UUID promise.
    return( deferred.promise() );
 
}
 

